home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!genesis.demon.co.uk
- From: Lawrence Kirby <fred@genesis.demon.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: accessing structures (newbie question)
- Date: Mon, 19 Feb 96 19:34:08 GMT
- Organization: none
- Message-ID: <824758448snz@genesis.demon.co.uk>
- References: <4g8gic$o6u@news1.sunbelt.net> <3128FA60.5227@metagen.co.uk>
- Reply-To: fred@genesis.demon.co.uk
- X-NNTP-Posting-Host: genesis.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.27
- X-Mail2News-Path: genesis.demon.co.uk
-
- In article <3128FA60.5227@metagen.co.uk> rws@metagen.co.uk "Rob Stenton" writes:
-
- >dking@SunBelt.Net wrote:
- >>
- >> Ok. having trouble accessing structure.
- >
- >There are basically two ways of accessing elements within a malloced
- >buffer:
- >1. Treat the malloced buffer as an array (as you suggested).
- >2. Increment a local pointer by sizeof(picture) in loop iteration.
-
- No, pointer arithmetic works in units of the object pointed to so to move
- onto the next element of an array you always add 1 to the corresponding
- pointer.
-
- >The first method is preferable because the second method involves pointer
- >arithmetic (always best avoided) which can cause problems on different
- >memory architectures and assumes things about BYTE sizes (but usually
- >works).
-
- If you follow the rules pointer arithmetic is guaranteed to work. In fact
- array indexing is defined in terns pfo pointer arithmetic i.e. a[i] is
- defined to be evaluated as *((a)+(i))
-
- >I think you may have been using the wrong syntax when you tried the array
- >method. The xth item is given by 'photos[x].' which is equivalent to
- >'(photos + x * sizeof(picture))->'.
-
- It is equivalent to (photos + x)->
-
- >The two ways for solving this problem are therefore:
- >1. (Recommended)
- > for (x=0;x<num_of_files;x++)
- > {
- > strncpy(photos[x].filename, filelist[x],12);
- > strncpy(photos[x].diskname, inputdisk,12);
- > strncpy(photos[x].indexname, inputindex,12);
- > }
-
- strncpy may not be what is required here (or in the original). It does
- *not* guarantee that what you end up with is a string (i.e. null terminated).
-
- >or
- >2. (Not recommended)
- > for (x=0;x<num_of_files;x++)
- > {
- > strncpy((photos + x * sizeof(picture))->filename,
- >filelist[x],12);
- > strncpy((photos + x * sizeof(picture))->diskname,
- >inputdisk,12);
- > strncpy((photos + x * sizeof(picture))->indexname,
- >inputindex,12);
- > }
-
- Remove the * sizeof(picture) and this is entirely equivalent to the first
- way (although I agree that the first way is clearer).
-
- --
- -----------------------------------------
- Lawrence Kirby | fred@genesis.demon.co.uk
- Wilts, England | 70734.126@compuserve.com
- -----------------------------------------
-